package com.mall.mall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.mall.common.To.SkuInfoTO;
import com.mall.common.utils.R;
import com.mall.mall.cart.feign.ProductFeignService;
import com.mall.mall.cart.interceptor.CartInterceptor;
import com.mall.mall.cart.service.CartService;
import com.mall.mall.cart.vo.Cart;
import com.mall.mall.cart.vo.CartItem;
import com.mall.mall.cart.vo.UserInfoTO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    private final String CART_PREFIX = "wtmall:cart";

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String result = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(result)){
            // 1、 远程查询当前要添加的商品信息
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                R skuInfo = productFeignService.info(skuId);
                SkuInfoTO skuInfoItem = (SkuInfoTO) skuInfo.getData("skuInfo", new TypeReference<SkuInfoTO>(){});
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(skuInfoItem.getSkuDefaultImg());
                cartItem.setTitle(skuInfoItem.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(skuInfoItem.getPrice());
            }, executor);

            // 2、远程查询 sku 的组合信息
            CompletableFuture<Void> getSkuSaleAttrValuesTask = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttrValues(skuSaleAttrValues);
            }, executor);

            CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrValuesTask).get();
            String s = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), s);

            return cartItem;
        }else {
            CartItem cartItem = JSON.parseObject(result, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));

            return cartItem;
        }

    }

    /**
     * 将商品添加到购物车
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String str = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(str, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        UserInfoTO userInfoTO = CartInterceptor.threadLocal.get();
        Cart cart= new Cart();
        if (userInfoTO.getUserId() != null){
            // 1、如果临时购物车里的数据还没有合并
            String tempCartKey = CART_PREFIX + userInfoTO.getUserKey();
            List<CartItem> tempCartItems = getCartItems(tempCartKey);
            if (!CollectionUtils.isEmpty(tempCartItems)){
                for (CartItem item : tempCartItems){
                    addToCart(item.getSkuId(), item.getCount());
                }
            }

            // 2、获取登录后的购物车的数据（包含合并过来的临时购物车的数据和登陆后的购物车的数据）
            String cartKey = CART_PREFIX + userInfoTO.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);

            // 3、清空临时购物车
            clearCart(tempCartKey);
        }else {
            // 2、没登录
            String cartKey = CART_PREFIX + userInfoTO.getUserKey();
            // 获取临时购物车的所有购物项
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }

        return cart;
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1);
        String s = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), s);
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItemCount(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    /**
     * 获取订单中，用户选中的所有商品
     * @return
     */
    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTO userInfoTO = CartInterceptor.threadLocal.get();
        if (null == userInfoTO.getUserId()){
            return null;
        }else {
            String cartKey = CART_PREFIX + userInfoTO.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            // 获取所有被选中的购物项
            List<CartItem> filteredCartItems = cartItems.stream().filter(cartItem -> cartItem.getCheck()).map(item->{
                // 更新价格
                R currentPrice = productFeignService.getPrice(item.getSkuId());
                item.setPrice(new BigDecimal((String) currentPrice.get("data")));
                return item;
            }).collect(Collectors.toList());
            return filteredCartItems;
        }
    }

    /**
     * 获取到要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTO userInfoTO = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTO.getUserId() != null){
            cartKey = CART_PREFIX + userInfoTO.getUserId();
        }else {
            cartKey = CART_PREFIX + userInfoTO.getUserKey();
        }

        return redisTemplate.boundHashOps(cartKey);
    }

    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);List<Object> values = hashOps.values();
        List<CartItem> collect = null;
        if (!CollectionUtils.isEmpty(values)){
            collect = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItem item = JSON.parseObject(str, CartItem.class);
                return item;
            }).collect(Collectors.toList());
        }
        return collect;
    }

    /**
     * 清空购物车
     */
    void clearCart(String cartKey){
        // redis 大键删除
        redisTemplate.delete(cartKey);
    }
}
